﻿using EasyFlow.Motion;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kimd.DMC3800Card
{
    public class DMC3800CardDigitalOperator : IDigitalIO
    {
        public bool IsError { get; set; }

        public string LastError { get; set; }

        public bool CheckApiResult(short rtn, string errMessage)
        {
            if (rtn != 0)
            {
                //_isApiErr = true;
                //MachineMessage.CallException(ExceptionType.FatalErr, "轴卡", errString, MachineErrCode.CardErr);
                //LogHelper.Error("运动控制卡", err, null);
                return false;
            }
            return true;
        }

        public void ClearOutBitStatus(short cardNo, short bitNo)
        {
            CheckApiResult(csLTDMC.LTDMC.dmc_write_outbit((ushort)cardNo, (ushort)bitNo, (ushort)1), "设置通用输出失败!");
        }

        public bool GetInBitStatus(short cardNo, short bitNo)
        {
            bool[] sts = GetInPortStatus(cardNo);
            return sts[bitNo];
        }

        public bool[] GetInPortStatus(short cardNo)
        {
            uint sts = csLTDMC.LTDMC.dmc_read_inport((ushort)cardNo, 0);
            bool[] insts = new bool[16];
            for (int i = 0; i < 16; i++)
            {
                insts[i] = ((sts >> i) & 0x01) == 0;
            }
            return insts;
        }

        public bool GetOutBitStatus(short cardNo, short bitNo)
        {
            bool[] sts = GetOutPortStatus(cardNo);
            return sts[bitNo];
        }

        public bool[] GetOutPortStatus(short cardNo)
        {
            uint sts = csLTDMC.LTDMC.dmc_read_outport((ushort)cardNo, 0);
            bool[] outsts = new bool[16];
            for (int i = 0; i < 16; i++)
            {
                outsts[i] = ((sts >> i) & 0x01) == 0;
            }
            return outsts;
        }

        public void SetOutBitStatus(short cardNo, short bitNo)
        {
            CheckApiResult(csLTDMC.LTDMC.dmc_write_outbit((ushort)cardNo, (ushort)bitNo, (ushort)0), "设置通用输出失败!");
        }
    }
}
